#!/usr/bin/env python
#
# IMHEAD--print all the information in the header for an image
#
# Author                 Version      Date
# -----------------------------------------------
# S M Crawford (SAAO)    0.1          31 Jul 2007

import os
import sys
import string
import pyfits

def imhead(inimg, ext=-1):
   """
   Print out all of the header information for a file

   inimg--name of a fits file
   ext--extension in inimg.  Set to -1 to print all extensions

   Returns 
   """

   #open image to be read
   infits=pyfits.open(inimg)

   #Determine the number of extensions
   next=len(infits)
   print ext
   #either process a single extension or multiple extensions
   if ext==-1:
      for i in range(next):  
          printheader(infits,i)
   else: 
      printheader(infits,ext)

   return 

def printheader(hdu,i):
    """Prints out each card in the header of an extension of an hdu
       
       hdu--pyfits hduList instance
       i  --extension
    """
    if i==0:  
      print '\n----------Header information in Primary Extension----------\n'
    else:
      print '\n----------Header information for Extension %i----------\n' % i
    header=infits[i].header
    for card in header.ascardlist():
      card=str(card).lstrip()
      if card:
	print card


if __name__ == "__main__":
        from getopt import getopt
        ext=-1
        opts=getopt(sys.argv[1:],'e:' ) 
        if len(opts[1]):
            myimg=opts[-1][0]
	    if len(opts[0]):
	     for op in opts[0]:	
		if op[0]=='-e': ext=int(op[1])
            print myimg, ext
	    imhead(myimg, ext) 
	else:
	    print imhead.__doc__
